package me.zhangsanfeng.gpss.service.impl;

import me.zhangsanfeng.gpss.common.entity.Sorter;
import me.zhangsanfeng.gpss.common.utils.QueryConditionUtil;
import me.zhangsanfeng.gpss.common.utils.UpdateUtil;
import me.zhangsanfeng.gpss.dao.BrandRepository;
import me.zhangsanfeng.gpss.entity.Brand;
import me.zhangsanfeng.gpss.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
@Transactional
public class BrandServiceImpl implements BrandService {

    @Autowired
    private BrandRepository repository;

    @Override
    public Brand insert(Brand brand) {
        return repository.save(brand);
    }

    @Override
    public List<Brand> insertBatch(List<Brand> brands) {
        return repository.saveAll(brands);
    }

    @Override
    public void delete(Brand brand) {
        repository.delete(brand);
    }

    @Override
    public void deleteBatch(List<Brand> brands) {
        repository.deleteAll(brands);
    }

    @Override
    public Brand update(Brand brand) {

        UpdateUtil.copyNullProperties(repository.getOne(brand.getId()),brand);
        return repository.saveAndFlush(brand);
    }

    @Override
    public List<Brand> updateBatch(List<Brand> brands) {
        for (Brand brand : brands) {
            UpdateUtil.copyNullProperties(repository.getOne(brand.getId()),brand);
        }
        return repository.saveAll(brands);
    }

    @Override
    public Brand selectOne(Brand brand) {
        return repository.findOne(Example.of(brand)).get();
    }

    @Override
    public List<Brand> selectList(Brand brand) {
        /*排序标识*/
        Sorter sorter = brand.getSorter();

        Map<String, Object> condition;
        //不排序
        if (null == sorter.getDesc() && null == sorter.getAsc() && null == sorter.getPrior()) {
            condition = QueryConditionUtil.getWhereCondition(brand, false, false);
        } else {
            condition = QueryConditionUtil.getWhereCondition(brand, false, true);
        }

        return QueryConditionUtil.getQueryInstanceOfList(condition, repository);
    }

    @Override
    public Page<Brand> selectPage(Brand brand) {
        /*排序标识*/
        Sorter sorter = brand.getSorter();

        Map<String, Object> condition;
        if (null == sorter.getDesc() && null == sorter.getAsc() && null == sorter.getPrior()){
            condition = QueryConditionUtil.getWhereCondition(brand, true, false);
        }else {
            condition = QueryConditionUtil.getWhereCondition(brand, true, true);
        }

        return QueryConditionUtil.getQueryInstanceOfPage(condition,repository);
    }
}
